package com.anjufang.controller.system;

import java.util.List;
import java.util.Set;

import com.anjufang.common.exception.PHException;
import com.anjufang.controller.BaseController;
import com.anjufang.entity.AdminMenu;
import com.anjufang.service.system.AdminMenuService;
import com.anjufang.service.system.ShiroService;
import com.anjufang.utils.Result;
import com.anjufang.utils.StringUtils;
import com.anjufang.utils.TokenManager;
import com.anjufang.utils.constant.Constant;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.anjufang.utils.constant.Constant.MenuType;

import com.baomidou.mybatisplus.mapper.EntityWrapper;


@RestController
@RequestMapping("/sys/menu/")
public class MenuController extends BaseController {
	@Autowired
	private ShiroService shiroService;
	@Autowired
	private AdminMenuService menuService;

	/**
	 * 导航菜单
	 */
	@RequestMapping("nav")
	public Result nav() {
		List<AdminMenu> menuList = menuService.getUserMenuList(TokenManager.getUserId());
		Set<String> permissions = shiroService.getUserPermissions(TokenManager.getUserId());
		return Result.ok().put("menuList", menuList).put("permissions", permissions);
	}
	/**
	 * 权限列表
	 * @return
	 */
	@RequestMapping("getPermissions")
	public Result getPermissions() {
		Set<String> permissions = shiroService.getUserPermissions(TokenManager.getUserId());
		return Result.ok().put("permissions", permissions);
	}
	/**
	 * 所有菜单列表
	 */
	@RequestMapping(value = LIST)
	public List<AdminMenu> list() {
		List<AdminMenu> menuList = menuService.menuList();
		return menuList;
	}

	/**
	 * 选择菜单(添加、修改菜单)
	 */
	@RequestMapping(value = SELECT)
	public Result select() {
		// 查询列表数据
		List<AdminMenu> menuList = menuService.selectList(new EntityWrapper<AdminMenu>().where("type != {0}", Constant.MenuType.BUTTON.getValue()));

		return Result.ok().put("menuList", menuList);
	}

	/**
	 * 菜单信息
	 */
	@RequestMapping("info/{id}")
	public Result info(@PathVariable("id") Long id) {
		AdminMenu menu = new AdminMenu().selectById(id);
		return Result.ok().put("menu", menu);
	}

	/**
	 * 保存
	 */
	@RequestMapping(value = SAVE)
	@RequiresPermissions("system/menu/save.htm")
	@Transactional
	public Result save(@RequestBody AdminMenu menu) {
		// 数据校验
		verifyForm(menu);
		// 添加地址长度判定
		String url = menu.getUrl();
		if (menu.getType() != 0 && (url.indexOf("/") == 0 || url.lastIndexOf(".") == 0)) {
			return Result.error("请填写正确的菜单地址！");
		}
		// 当菜单为一级菜单时，地址设为空
		if (menu.getType() == 0) {
			menu.setUrl(null);
		}
		menuService.addAndUpdateRolePerm(menu);
		if (menu.getParentId() != 0 && menu.getType() == 1) {
			// 添加长度判定
			String prefixName = "";
			if (menu.getName().length() <= 2) {
				prefixName = menu.getName();
			} else {
				prefixName = menu.getName().substring(0, menu.getName().length() - 2);
			}
			if (url.contains(".")) {
				String newUrl = url.substring(url.indexOf("/") + 1, url.lastIndexOf("."));
				AdminMenu addA = new AdminMenu("添加" + prefixName, newUrl + "/save.htm", 2, menu.getId(), "");
				AdminMenu addB = new AdminMenu("修改" + prefixName, newUrl + "/update.htm", 2, menu.getId(), "");
				AdminMenu addC = new AdminMenu("删除" + prefixName, newUrl + "/delete.htm", 2, menu.getId(), "");
				menuService.addAndUpdateRolePerm(addA);
				menuService.addAndUpdateRolePerm(addB);
				menuService.addAndUpdateRolePerm(addC);
			}
		}
		return Result.ok();
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = UPDATE)
	@RequiresPermissions("system/menu/update.htm")
	public Result update(@RequestBody AdminMenu menu) {
		// 数据校验
		verifyForm(menu);
		menu.updateById();
		return Result.ok();
	}

	/**
	 * 删除
	 */
	@RequestMapping(value = DELETE)
	@RequiresPermissions("system/menu/delete.htm")
	public Result delete(long id) {
		if (id <= 31) {
			return Result.error("系统菜单，不能删除");
		}
		// 判断是否有子菜单或按钮
		List<AdminMenu> menuList = menuService.selectList(new EntityWrapper<AdminMenu>().where("parent_id ={0}", id));
		if (menuList.size() > 1) {
			return Result.error("请先删除子菜单或按钮");
		}
		menuService.deleteBatch(new Long[] { id });

		return Result.ok();
	}

	/**
	 * 验证参数是否正确
	 */
	private void verifyForm(AdminMenu menu) {
		if (StringUtils.isBlank(menu.getName())) {
			throw new PHException("菜单名称不能为空");
		}

		if (menu.getParentId() == null) {
			throw new PHException("上级菜单不能为空");
		}

		// 菜单
		if (menu.getType() == MenuType.MENU.getValue()) {
			if (StringUtils.isBlank(menu.getUrl())) {
				throw new PHException("菜单URL不能为空");
			}
		}

		// 上级菜单类型
		int parentType = MenuType.CATALOG.getValue();
		if (menu.getParentId() != 0) {
			AdminMenu parentMenu = new AdminMenu();
			parentMenu = parentMenu.selectById(menu.getParentId());
			parentType = parentMenu.getType();
		}

		// 目录、菜单
		if (menu.getType() == MenuType.CATALOG.getValue() || menu.getType() == MenuType.MENU.getValue()) {
			if (parentType != MenuType.CATALOG.getValue()) {
				throw new PHException("上级菜单只能为目录类型");
			}
			return;
		}

		// 按钮
		if (menu.getType() == MenuType.BUTTON.getValue()) {
			if (parentType != MenuType.MENU.getValue()) {
				throw new PHException("上级菜单只能为菜单类型");
			}
			return;
		}
	}
}
